<template>
  <div class="result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      offset="10"
    >
      <article-cell :Newslist="list"></article-cell>
    </van-list>
  </div>
</template>

<script>
// 导入搜索结果api
import { searchResult } from '@/assets/api/search.js'

export default {
  name: 'result',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      error: false,
      // 搜索结果请求参数
      searchParams: {
        page: 1,
        q: ''
      },
      // 搜索的总条数
      total: 0
    }
  },
  methods: {
    async onLoad() {
      // 将搜索关键字赋值给请求参数
      this.searchParams.q = this.searchText
      // 发起请求拿到值
      try {
        var { data: res } = await searchResult(this.searchParams)
      } catch {
        // 对请求失败进行处理
        this.error = true
        return (this.loading = false)
      }
      // 将拿到的值赋予
      this.total = res.data.total_count
      this.list.push(...res.data.results)
      // 触发下一项
      this.searchParams.page++
      // 关闭加载
      this.loading = false
      if (!res.data.results.length) {
        this.finished = true
      }
    }
  }
}
</script>

<style lang="less" scoped></style>
